from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models

from django.core.paginator import Paginator

def tab():
    cates = models.Cates.objects.extra(select = {'newpath':'concat(paths,id)'}).order_by('newpath')
    for i in cates:
        num = i.paths.count(',')-1
        i.newname=num*'|----'
    return cates  

def addcate(request):
	if request.method == 'GET':
		# 将所有的类型返回
		cates = tab()

		return render(request,'myadmin/cate/addcate.html',{'cates':cates})
	elif request.method=='POST':
		pid = request.POST.get('pid')
		name = request.POST.get('name')
		print(pid)
		print(name)
		if pid=='0':
			cate = models.Cates()
			cate.name=name
			cate.upid=int(pid)
			cate.paths='0,'
			cate.save()
		else:
			pobj = models.Cates.objects.get(id=pid)
			c = models.Cates()
			c.name=name
			c.upid=pobj.id
			c.paths=pobj.paths+pid+','
			c.save()
	return redirect(reverse('myadmin_listcate'))
	
def catelist(request):
	cates = tab()

	types = request.GET.get('type')
	# 接受关键字
	search = request.GET.get('search')
	# 判断用是否搜索内容
	if types:
		if types == 'all':
			from django.db.models import Q
			cates = models.Cates.objects.filter(Q(id__contains=search)|Q(name__contains=search)|Q(upid__contains=search)|Q(paths__contains=search))
		elif types=='name':
			cates = models.Cates.objects.filter(name__contains=search)
		elif types=='upid':
			cates = models.Cates.objects.filter(upid__contains=search)
		elif types == 'paths':
			cates = models.Cates.objects.filter(paths__contains=search)
	# 实例化分页对象	
	p = Paginator(cates, 5)

	#一共可以分多少页
	sumpage=p.num_pages

	# 取第几页的数据
	# 接受用户的页码	
	page = int(request.GET.get('p',1))
	# 第几页的数据
	page1 = p.page(page)

	# 判断 如果用输入的页码<=3 显示前五个页码
	if page<=3:
	# 页码的迭代序列  [1,2,3,4,5,6,7]
		prange = p.page_range[:5]
	elif page+2>=sumpage:
		prange = p.page_range[-5:]
	else:
		prange = p.page_range[page-3:page+2]

	return render(request,'myadmin/cate/catelist.html',{'cates':page1,'prange':prange,'page':page,'sumpage':sumpage})


def delcate(request):
	pid = int(request.GET.get('pid'))

	cnum = models.Cates.objects.filter(upid=pid).count()
	if cnum:
		return JsonResponse({'msg':0})
	else:
		c = models.Cates.objects.get(id=pid)
		c.delete()
		return JsonResponse({'msg':1})

def editcate(request):
	cid = int(request.GET.get('id'))
	cname = request.GET.get('name')
	try:
		cate = models.Cates.objects.get(id=cid)
		cate.name=cname
		cate.save()
		return JsonResponse({'msg':1})
	except:
		return JsonResponse({'msg':0})






